<template>
<div>
  <el-row>
    <el-col :span="22">
      <h2 style="text-align: center;">批量新增用户</h2>
    </el-col>
    <el-col :span="2">
     <div style="margin-top: 20px">
       <el-button style="width: 100px;" type="primary"  @click="getBack">返回</el-button>
     </div>
    </el-col>
  </el-row>
 <el-row>
   <el-col :span="24">
     <div style="width: 1000px;margin: 0 auto 20px;display: flex;align-items: center">
       <div style="margin-right: 10px">二者选一 </div>
     <el-radio-group v-model="radio" @change="getRadio">
       <el-radio :label="0">单个新增</el-radio>
       <el-radio :label="1">批量新增</el-radio>
     </el-radio-group>
     </div>
   </el-col>
 </el-row>
<!--  <el-row ><el-col :span="24">-->
<!--   <div style="width: 1000px;margin: 0 auto 20px"> <el-button-->
<!--     style="width: 130px"-->
<!--     icon="el-icon-plus"-->
<!--     size="small"-->
<!--     type="primary"-->

<!--     plain-->
<!--     @click="handleUpload" >批量新增</el-button></div>-->
<!--  </el-col></el-row>-->
  <el-form v-if="isShow" ref="form" :model="form" :rules="rules" label-width="80px" >
    <el-row>
      <el-col :span="12">
        <el-form-item label="雇员姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入雇主姓名"/>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="用户性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择">
            <el-option
              v-for="dict in sexOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>

    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="证件类型" prop="idCardTypeId">
          <el-select v-model="form.idCardTypeId" placeholder="请选择">
            <el-option
              @click.native="getCardType(item)"
              v-for="item in idCardTypeList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
              :disabled="item.status === '0'"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="证件号码" prop="idCardNo">
          <el-input v-model="form.idCardNo" placeholder="请输入证件号码"/>
        </el-form-item>
      </el-col>

    </el-row>
    <el-row>
      <!--          TODO 做成选择-->
      <el-col :span="12">
        <el-form-item label="工种名称" prop="industryId">
          <treeselect style="width: 250px" v-model="form.industryId" @select="selectDepart" :options="industryOptions"
                      :normalizer="normalizer" placeholder="请选上级分类"/>
<!--          <el-select v-model="form.industryId" placeholder="请选择">-->
<!--            <el-option-->
<!--              v-for="item in TypeworkId"-->
<!--              :key="item.id"-->
<!--              :value="item.id"-->
<!--              :label="item.name"-->
<!--            />-->
<!--          </el-select>-->
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="健康情况" prop="healthCond">
          <el-select v-model="form.healthCond" placeholder="请选择">
            <el-option
              v-for="item in healthy"
              :key="item.dictValue"
              :value="item.dictValue"
              :label="item.dictLabel"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="月收入" prop="incomeMonth">
          <el-input v-model="form.incomeMonth" placeholder="请输入月收入"/>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="保费" prop="price">
          <el-input v-model="form.price" placeholder="请输入保费"/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="职务名称" prop="position">
          <el-input v-model="form.position" placeholder="请输入职务名称"/>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="用工单位" prop="company">
          <el-input v-model="form.company" placeholder="请输入用工单位"/>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="18">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="5" placeholder="请输入备注内容"/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item label="状态 " prop="status">
      <el-radio-group v-model="form.status">
        <el-radio
          v-for="dict in statusOptions"
          :key="dict.dictValue"
          :label="dict.dictValue"
        >{{ dict.dictLabel }}
        </el-radio>
      </el-radio-group>
    </el-form-item>
    <div  class="dialog-footer">
      <el-button @click="cancel('form')">重置</el-button>
      <el-button type="primary" @click="submitForm('form')">确 定</el-button>

    </div>
  </el-form>
<!--  <el-dialog :title="upload.title" :visible.sync="upload.open1" width="900px" append-to-body>-->
  <div v-else style="margin:50px auto 0;width: 800px;text-align: center">
<!--     accept=".csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"-->
    <el-upload
      ref="upload"
      class="upload-demo"
      action="/"
      :limit="1"
      :on-exceed="formHandleExceed"
      :file-list="formFileList"
      :on-remove="formHandleRemove"
      :http-request="handleUpdateForm"
      :before-upload="beforeUploadForm"
      :on-success="successform"
      :on-change="uploadChange"
      :auto-upload="false"
      drag
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <div class="el-upload__tip" slot="tip">
        <el-checkbox v-model="upload.isSupportUpdate" />是否更新已经存在的用户数据
        <el-link type="info" style="font-size:12px;color: #00afff" @click="importTemplate">下载模板</el-link>
      </div>
      <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
    </el-upload>
    <div slot="footer" style="display: flex;justify-content: flex-end">
      <el-button type="primary" style="width: 100px" @click="submitFileForm">确 定</el-button>
      <el-button style="width: 100px" @click="upload.open1 = false">取 消</el-button>
    </div>
  </div>
<!--  </el-dialog>-->
</div>
</template>

<script>
import {addUser, updateUser, getUser, importTemolate, batchSave} from "@/api/insurance/user";
import {listIdCardType} from "@/api/base/idCardType";
import {listIndustry} from "@/api/insurance/industry";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";


export default {
  name: "userAdd",
  data(){
    return{
      //选择新增条件
      radio:0,
      isShow:true,//二者选一
      // 状态 字典
      statusOptions: [],
      formMaxSize: 10,//上传文件大小
      formFileList:[],
      uploadFormFileList: [],//确定上传文件
      //性别  字典
      sexOptions: [],
      //证件类型
      idCardTypeList: [],
      // 表单参数
      form: {
        insureId:null, //投保id
        id: null,
        name: null,//雇主姓名
        sex: null,//性别
        idCardTypeId: 1,//证件类型
        idCardTypeName: null,//证件类型名称
        idCardNo: null,//证件号码
        industryId: null,//工种id(1:1-3类；2：4类)
        industryName: null,//健康情况
        healthCond:'1',//健康情况
        incomeMonth: null,//月收入
        company: null,//用工单位
        position: null,//职务名称
        remark: null,//备注
        price: null,//保费
        createTime: null,//
        updateTime: null,
        status: "0"
      },
      // 表单校验
      rules: {
        name:[
          { required: true, message: '请输入雇主姓名', trigger: 'blur' },
        ],
        sex:[
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        idCardTypeId:[
          { required:true, message: '请选择证件类型', trigger: 'change' }
        ],
        idCardNo: [
          {required: true, message: "证件号码不能为空", trigger: "blur"}
        ],
        industryId:[
          { required:true, message: '请选择工种名称', trigger: 'change' }
        ],
        healthCond:[
          { required:true, message: '请选择健康情况', trigger: 'change' }
        ],
        incomeMonth:[
          {required: true, message: "请输入月收入", trigger: "blur"}
        ],
        price:[
          {required: true, message: "请输入保费", trigger: "blur"}
        ],
        position:[
          {required: true, message: "请输入职务名称", trigger: "blur"}
        ],
        company:[
          {required: true, message: "请输入用工单位", trigger: "blur"}
        ],
        remark:[
          {required: false, message: "请输入用工单位", trigger: "blur"}
        ],
        status:[
          {
            required: true, message: '请选择状态', trigger: 'change' }

        ],

      },
      healthy:[],//健康状况
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open1: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否更新已经存在的用户数据
        isSupportUpdate: false,
      },
      // 职业分类树选项
      industryOptions: [],
    }
  },
  created() {
    // this.form.insureId=this.$store.state.user.infoUser.id;
    var infoUser=this.$route.query.infoUser;
    if (infoUser!=undefined){
      this.form.insureId=infoUser.id

    }
    // console.log('insureId', this.form.insureId)
    this.getDicts("common_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_user_sex").then(res => {
      this.sexOptions = res.data;
    });
    this.getDicts("health_cond").then(res => {
      this.healthy = res.data;
     // console.log('healthy', this.healthy)
    });
    this.getDicts("health_cond").then(res => {
      this.healthOptions = res.data;
    });
    this.getDicts("industry_type").then(res => {
      this.industryTypeOptions = res.data;
    });
    this.getIdcardTypeList();
    this.getTreeselect();
  },
  components: {
    Treeselect
  },
  methods:{
    getRadio(e){
      // console.log('eee',e)
      if (e==0){
        this.isShow=true;
      }else {
        this.isShow=false;
      }
    },
    //上传成功的
    successform(res,file,fileName){
      // console.log('res',res)
      // console.log('file',file)
      // console.log('fileName',fileName)
    },
    /** 转换职业分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },

    /** 查询部门下拉树结构 */
    getTreeselect() {
      listIndustry().then(response => {
        this.industryOptions = [];
        const data = {id: 0, name: '顶级节点', children: []};
        data.children = this.handleTree(response.data, "id", "parentId");
        this.industryOptions.push(data);
        // console.log('工种名称', response);
        // console.log('industryOptions', this.industryOptions);
      });
    },
    //选择工种名称
    selectDepart(e) {
      this.form.industryName = e.name
    },
    //上传文件导入
    handleUpload() {
      this.upload.title = "投保用户批量添加";
      this.upload.open1 = true;
    },
    //开始上传前验证
    beforeUploadForm(file) {
      // console.log('验证', file)
      //文件大小验证
      if (file.size / 1024 / 1024 > this.formMaxSize) {
        this.$message({
          message: `上传文件大小不能超过${this.formMaxSize}M!`,
          type: 'waning'
        })
        false
      }
      //  中文乱码处理
      if (file.raw) {
        let reader = new FileReader()//读取文件内容
        reader.readAsText(file.raw, 'gb2312')//防止中文乱码问题，不加reader.onload方法都不会触发
        reader.onload = function (e) {
          this.contentHtml = e.target.result;//txt文本内容，接下来就可以对其进行校验处理了
          // console.log('contentHtml', this.contentHtml);
        }
      }
      //验证文件类型
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = testmsg === 'xlsx' || testmsg === 'xls' || testmsg === 'csv'
      if (!extension) {
        this.$message({
          message: '上传文件只能是xlsx/xls/csv格式',
          type: 'warning'
        })

      }
      return extension
    },
    //移除上传列表中的文件
    formHandleRemove(file, formFileList) {
      let that = this;
      for (let i = 0; i < that.uploadFormFileList.length; i++) {
        if (that.uploadFormFileList[i].pname === file.name) {
          that.uploadFormFileList.splice(i, 1);
          break;
        }
      }
    },
    // 下载文件
    importTemplate(){
      var obj={
       type:'1'
      }
      importTemolate(obj).then(res=>{
        // console.log('用户批单模板',res)
        this.download(res.msg);
      })
    },
    //上传导入确定按钮
    submitFileForm(){
      this.$refs.upload.submit();
      // this.$refs.upload.submit();
    },
    // 允许上传文件个数验证
    formHandleExceed(files, formFileList) {
      // console.log('files', files)
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + formFileList.length} 个文件`)
    },
    //上传文件
    uploadChange(file,fileList){
     // console.log('file5',file)
     //  console.log('fileList5',fileList)

    },
    //上传文件
    handleUpdateForm(param) {
      // console.log('param', param)
      // console.log('isSupportUpdate',this.upload)
      let that = this;
      let formData = new FormData();
      // console.log('id', that.form.insureId)
      formData.append('id', that.form.insureId)//额外参数
      formData.append('file',param.file);
      formData.append('isSupportUpdate',that.upload.isSupportUpdate)
      // console.log('param', formData);
      batchSave(formData).then(response => {
        // console.log('1111', response)
        var obj={
          id:this.form.insureId
        }
        this.upload.open1 =false;

        if (response.code==200 && response.msg=='操作成功'){
         setTimeout(()=>{
           this.$router.push({
             path:'/business/user/index',
             query:{
               insureInfo:obj
             }
           })
         },2000)
          this.$message({
                message: '批量添加成功',
                type: 'success'
              });
        }else if (response.code==200 && response.msg!='操作成功'){
          this.$message({
            message: '批量添加成功',
            type: 'success'
          });
          this.$alert('是否要将添加用户部分错误的信息导出', '标题名称', {
                confirmButtonText: '确定',
                callback: action => {
                  if (action=='confirm'){
                    let link = document.createElement('a'); // 创建a标签
                    link.style.display = 'none';
                    let objectUrl = response.msg;
                    link.href = objectUrl;
                    link.click();
                    setTimeout(()=>{
                      this.$router.push({
                        path:'/business/user/index',
                        query:{
                          insureInfo:obj
                        }
                      })
                    },2000)
                  }
                }
                });
          }

        // console.log('res23', response.size)

        // if (response.size!=0 && response.size!=114){
        //   this.$alert('是否要将添加用户部分错误的信息导出', '标题名称', {
        //     confirmButtonText: '确定',
        //     callback: action => {
        //       console.log('action',action)
            //   if (action=='confirm'){
            //   let blob = new Blob([response], { type: 'application/vnd.ms-excel;charset=utf-8' }); //type为所需要下载的文件格式，以xls文件为例
            //   console.log('blob',blob)
            //   // console.log('blob1:',blob.size)
            //   // 浏览器兼容，Google和火狐支持a标签的download，IE不支持
            //   if (window.navigator && window.navigator.msSaveBlob) {
            //     //IE浏览器、微软浏览器
            //     /* 经过测试，微软浏览器Microsoft Edge下载文件时必须要重命名文件才可以打开，
            //       IE可不重命名，以防万一，所以都写上比较好 */
            //     window.navigator.msSaveBlob(blob, '文件.xls');
            //   } else {
            //     //其他浏览器
            //     let link = document.createElement('a'); // 创建a标签
            //     link.style.display = 'none';
            //     let objectUrl = URL.createObjectURL(blob);
            //     link.href = objectUrl;
            //     link.click();
            //     URL.revokeObjectURL(objectUrl);
            //   }
            //   this.$router.push({
            //     path:'/business/user/index',
            //     query:{
            //       insureInfo:obj
            //     }
            //   })
            // }
            // }
          // });
        //   this.$message({
        //     message: '批量添加成功',
        //     type: 'success'
        //   });
        // } else  if(response.size==114){
        //   this.$message.error('上传失败,以下证件号码存在重复,请修改后重新操作');
        //
        // } else {
        //   this.$router.push({
        //     path:'/business/user/index',
        //     query:{
        //       insureInfo:obj
        //     }
        //   })
        //   this.$message({
        //     message: '批量添加成功',
        //     type: 'success'
        //   });
        // }


      })
    },
    //查询证件类型
    getIdcardTypeList() {
      listIdCardType().then(res => {
        this.idCardTypeList = res.rows
      })
    },
    //取消
    cancel(form){
    this.$refs[form].resetFields();
    },
    //点击对应的证件类型
    getCardType(item){
      this.form.idCardTypeId = item.id;
      this.form.idCardTypeName = item.name;
      // console.log('item',item)
    },
    getBack(){
      this.$router.back(-1);
    },
    submitForm(form){
      var obj={
        id:this.form.insureId
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
            // console.log('form', this.form);
            addUser(this.form).then(response => {
              this.msgSuccess("新增成功");
              // this.open = false;
              this.$router.push({
                path:'/business/user/index',
                query:{
                  insureInfo:obj
                }
              })
              // console.log('新增', response)
              // this.getQueryUser();
            });
        }
      });
    }
  }
}
</script>

<style scoped>
.el-form{
  width: 1000px;
  /*height: 800px;*/
  margin: 0 auto;
  /*background-color: #4AB7BD;*/
}
.dialog-footer{
  /*background-color: pink;*/
  text-align: center;
}
.el-input{
  width: 220px;
}
.el-button{
  width: 200px;
}
</style>
